package service

import (
	"AiBus/global"
	"AiBus/model"
	"AiBus/request"
	"AiBus/utils"
	"github.com/gin-gonic/gin"
)

func CheckGrants(c *gin.Context) {
	openCode := c.GetString("open_id")
	grants := utils.Credit_grants()
	grantsInfo := model.Grants{
		TotalGranted:   grants.TotalGranted,
		TotalAvailable: grants.TotalAvailable,
		UserId:         openCode,
	}
	tx := global.App.DB.Where("user_id=?", openCode).First(&model.Grants{})
	if tx.Error != nil {
		// 没有数据，则添加
		tx := global.App.DB.Create(&grantsInfo)
		if tx.Error != nil {
			utils.Fail(c, 403, "余额获取失败")

		} else {
			utils.Success(c, 0, grantsInfo)
		}
	} else {
		//存在对应的用户数据，则更新
		tx = global.App.DB.Model(&model.Grants{}).Where("user_id=?", openCode).Updates(&model.Grants{
			TotalGranted:   grants.TotalGranted,
			TotalAvailable: grants.TotalAvailable,
		})
		if tx.Error != nil {
			utils.Fail(c, 403, "余额获取失败")

		} else {
			utils.Success(c, 0, request.Greditgrants{
				Object:         grants.Object,
				TotalGranted:   grants.TotalGranted,
				TotalUsed:      grants.TotalUsed,
				TotalAvailable: grants.TotalAvailable,
			})
		}

	}

}
